package cn.qg.auth.controller;

import cn.qg.auth.excetion.LoginFailedException;
import cn.qg.auth.service.qguser.QgUserService;
import cn.qg.auth.service.token.TokenService;
import cn.qg.beans.dto.Dto;
import cn.qg.beans.pojo.QgUser;
import cn.qg.beans.vo.QgTokenVo;
import cn.qg.common.DtoUtil;
import cn.qg.common.EmptyUtils;
import cn.qg.common.ErrorCode;
import cn.qg.common.MD5;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import java.util.Date;

/**
 * 11:12
 */
@RestController

public class LoginController {
    @Resource
    QgUserService qgUserService;
    @Resource
    TokenService tokenService;

    //普通登录
    @RequestMapping(value = "/api/dologin",method = RequestMethod.POST,produces = {"application/json"})
    public Dto doLogin(@RequestParam String phone, @RequestParam String password) throws LoginException {
        System.out.println("成功进入");

        try {
            //判断是否为空
            if(EmptyUtils.isEmpty(phone)||EmptyUtils.isEmpty(password)){
                throw new LoginFailedException("用户名或密码不能为空！");
            }
            //用户验证
            QgUser qgUse= qgUserService.login(phone, password);
            //判断用户是否存在
            if(EmptyUtils.isEmpty(qgUse)){
                throw new LoginFailedException("用户名或密码错误！");
            }
            //根据用户生成token
            String token = tokenService.generateToken(qgUse);
            //将token存入redis中
            tokenService.saveToken(token,qgUse);
            //创建后台输出对象
            QgTokenVo qgTokenVo = new QgTokenVo(token,new Date().getTime()+TokenService.TOKEN_EXPIRE_TIME * 1000,new Date().getTime());
           //利用dto 返回数据
            return DtoUtil.returnDataSuccess(qgTokenVo);
        }catch (LoginFailedException e){
            e.getMessage();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_AUTHENTICATION_FAILED);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("登录失败！请重试！",ErrorCode.AUTH_UNKNOWN);
        }


    }


    @RequestMapping(value = "/api/test")
    public String test(){
        System.out.println("lllllllllllllll");
        return "";
    }


}
